/*
 * @Description:
 * @version: 1.0.0
 * @Author: YinJianFeng
 * @Date: 2024-03-22 13:34:43
 */
const svgstore = require('svgstore');
const walker = require('folder-walker');
const fs = require('fs');
const { JSDOM } = require('jsdom');

const iconDir = './src/assets/svg-icons';
const iconfontsPath = './src/svg-icons.js';

const iconFonts = svgstore();

let iconCount = 0;
console.log(`Packing SVG icons under directory ${iconDir} to iconfonts ...`);
const stream = walker([iconDir]);
stream
  .on('data', (data) => {
    if (data.type === 'file' && data.basename.endsWith('.svg')) {
      console.log(data.relname);
      const symbolId = data.relname.replaceAll('\\', '/').replace(/\.svg$/, ''); // from DOS style to UNIX style
      console.log(`Load icon: ${symbolId}`);

      const dom = new JSDOM(fs.readFileSync(data.filepath, 'utf8'));
      const svgElement = dom.window.document.querySelector('svg');

      svgElement
        .querySelectorAll('path, ellipse, circle, rect')
        .forEach((path) => {
          if (!path.getAttribute('fill') && !path.getAttribute('stroke')) {
            path.setAttribute('fill', '#27292A');
          }
          if (!path.getAttribute('fill')) {
            path.setAttribute('fill', 'none');
          }
        });

      iconFonts.add(symbolId, dom.serialize());
      iconCount++;
    }
  })
  .on('end', () => {
    const text = iconFonts.toString({ inline: true }).replace(/[\r\n]/gm, '');
    //fs.writeFileSync('./iconFonts.svg', text);
    console.log(`Total ${iconCount} icons loaded.`);
    fs.writeFileSync(
      iconfontsPath,
      `/* eslint-disable */\n!function(l){var a,h,c,m,t,z='${text}',i=(i=document.getElementsByTagName("script"))[i.length-1].getAttribute("data-injectcss"),o=function(l,a){a.parentNode.insertBefore(l,a)};if(i&&!l.__iconfont__svg__cssinject__){l.__iconfont__svg__cssinject__=!0;try{document.write("<style>.svgfont {display: inline-block;width: 1em;height: 1em;fill: currentColor;vertical-align: -0.1em;font-size:16px;}</style>")}catch(l){console&&console.log(l)}}function v(){t||(t=!0,c())}function d(){try{m.documentElement.doScroll("left")}catch(l){return void setTimeout(d,50)}v()}a=function(){var l,a;(a=document.createElement("div")).innerHTML=z,z=null,(l=a.getElementsByTagName("svg")[0])&&(l.setAttribute("aria-hidden","true"),l.style.position="absolute",l.style.width=0,l.style.height=0,l.style.overflow="hidden",a=l,(l=document.body).firstChild?o(a,l.firstChild):l.appendChild(a))},document.addEventListener?~["complete","loaded","interactive"].indexOf(document.readyState)?setTimeout(a,0):(h=function(){document.removeEventListener("DOMContentLoaded",h,!1),a()},document.addEventListener("DOMContentLoaded",h,!1)):document.attachEvent&&(c=a,m=l.document,t=!1,d(),m.onreadystatechange=function(){"complete"==m.readyState&&(m.onreadystatechange=null,v())})}(window);`,
    );
    console.log(`Saved iconfonts to ${iconfontsPath} .`);
  });
